package ext.tianma.project2.APQP.controller;

import java.io.PrintWriter;
import java.util.Locale;
import java.util.Vector;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import wt.org.WTPrincipal;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.workflow.engine.WfProcess;
import wt.workflow.work.WorkItem;
import ext.com.workflow.WorkflowUtil;
import ext.tianma.project2.APQP.service.APQPPlanActivityService;
import ext.tianma.project2.APQP.service.APQPProjectService;
import ext.tianma.project2.APQP.service.ProcessService;
import ext.tianma.util.TMUtil;

/**
 * 类名: APQPController </br>
 * 包名: ext.tianma.project2.APQP.controller
 * 描述: APQP Controller类
 * @author xucr
 * 创建时间: 2020年8月13日
 * 发布版本: V1.0
 */

@Controller
@RequestMapping({ "/ProcessController" })
public class ProcessController {
	
	@Autowired
	APQPProjectService projectservice;
	
	@Autowired
	APQPPlanActivityService planactivityservice;
	
	@Autowired
	ProcessService processService;
	
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ProcessController.class);

	/**
	 * 发起流程
	 * @param planactivityOid
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年8月20日
	 */
	@RequestMapping(value = "/launchApplyWorkflow", method = { RequestMethod.POST, RequestMethod.GET })
	public void launchApplyWorkflow(
			@RequestParam(value = "projectOid", required = false) String projectOid,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("text/html;charset=UTF-8");
		TMUtil.setHeader(response);
		PrintWriter out = response.getWriter();
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			JSONObject obj = new JSONObject();
			/**
			 * 校验
			 * 1、项目在流程中时，不能启动流程
			 * 2、
			 * 
			 * 功能说明
			 * 1、 构建process与project2的关系:formdataxml表
			 * 2、 存储project2的信息，用于流程查询：formdataxml表
			 * 3、 存储planactivity的信息，用于流程查询：formdataxml表
			 * */

			obj.put("code", "1");
			obj.put("msg", "流程功能待开发");
			out.print(obj.toString());
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 完成任务
	 * @param workItemOid
	 * @param wfprocessOid
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年8月20日
	 */
	@RequestMapping(value = "/completTask", method = { RequestMethod.POST, RequestMethod.GET })
	public void completTask(
			@RequestParam(value = "params",required=false) String params,
			HttpServletResponse response) throws Exception {
		logger.info("completTask >>>> params：" + params);
		response.setContentType("text/html;charset=UTF-8");
		TMUtil.setHeader(response);
		PrintWriter out = response.getWriter();
		WTPrincipal enforce2 = SessionHelper.manager.setAdministrator();
		try {
			JSONObject paramsObj = new JSONObject(params);
			String tip = "";
			String workItemOid = "";
			if(paramsObj.has("workItemOid")) {
				workItemOid = paramsObj.getString("workItemOid");
			} else {
				tip = "请选择有效的流程任务";
			}
			
			if(StringUtils.isEmpty(tip)) {
				String comments = "";
				if(paramsObj.has("comments")) {
					comments = paramsObj.getString("comments");
				}
				
				String event = "";
				if(paramsObj.has("event")) {
					event = paramsObj.getString("event");
				} else {
					event = "COMPLETED";
				}
				
				Vector<String> eventList = new Vector<String>();
	        	eventList.add(event);
	        	processService.completeTask(workItemOid, comments, eventList);
	        	
	        	WorkItem workitem = (WorkItem) TMUtil.oid2Obj(workItemOid);
	        	WfProcess process = WorkflowUtil.getProcess(workitem);
	        	
	        	//处理数据
	        	processService.updateDate(process);
			}
			
			JSONObject obj = new JSONObject();
			obj.put("code", StringUtils.isNotEmpty(tip) ? "0" : "1");
			obj.put("msg",  tip);
			out.print(obj.toString());
		} finally {
			SessionHelper.manager.setPrincipal(enforce2.getName());
		}
	}
	
//	/**
//	 * 查看流程之APQP信息
//	 * @param workItemOid
//	 * @param wfprocessOid
//	 * @param response
//	 * @throws Exception
//	 * @author xucr
//	 * @CreateDate 2020年8月20日
//	 */
//	@RequestMapping(value = "/findProcessOfProject", method = { RequestMethod.POST, RequestMethod.GET })
//	public void findProcessOfProject(
//			@RequestParam(value = "workItemOid", required = false) String workItemOid,
//			@RequestParam(value = "wfprocessOid", required = false) String wfprocessOid,
//			HttpServletResponse response) throws Exception {
//		
//		response.setContentType("text/html;charset=UTF-8");
//		TMUtil.setHeader(response);
//		PrintWriter out = response.getWriter();
//		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
//		try {
//			JSONObject xmlInfo = processService.getFormDataXml(wfprocessOid);
//			JSONObject obj = null;
//			if(null != xmlInfo) {
//				obj = xmlInfo.getJSONObject(ProcessService.PROJECTiNFO);
//			} else {
//				obj = new JSONObject();
//			}
//			out.print(obj.toString());
//		} finally {
//			SessionServerHelper.manager.setAccessEnforced(enforce);
//		}
//	}
//	
//	/**
//	 * 查看流程之活动信息
//	 * @param workItemOid
//	 * @param wfprocessOid
//	 * @param response
//	 * @throws Exception
//	 * @author xucr
//	 * @CreateDate 2020年8月20日
//	 */
//	@RequestMapping(value = "/findProcessOfActivity", method = { RequestMethod.POST, RequestMethod.GET })
//	public void findProcessOfActivity(
//			@RequestParam(value = "workItemOid", required = false) String workItemOid,
//			@RequestParam(value = "wfprocessOid", required = false) String wfprocessOid,
//			HttpServletResponse response) throws Exception {
//		
//		response.setContentType("text/html;charset=UTF-8");
//		TMUtil.setHeader(response);
//		PrintWriter out = response.getWriter();
//		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
//		try {
//			JSONObject xmlInfo = processService.getFormDataXml(wfprocessOid);
//			JSONObject obj = null;
//			if(null != xmlInfo) {
//				obj = xmlInfo.getJSONObject(ProcessService.ACTIVITYSINFO);
//			} else {
//				obj = new JSONObject();
//			}
//			out.print(obj.toString());
//		} finally {
//			SessionServerHelper.manager.setAccessEnforced(enforce);
//		}
//	}
	
	/**
	 * 查询流程详情
	 * @param workItemOid
	 * @param wfprocessOid
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年8月31日
	 */
	@RequestMapping(value = "/findProcessInfo", method = { RequestMethod.POST, RequestMethod.GET })
	public void findProcessInfo(
			@RequestParam(value = "params", required = false) String params,
			HttpServletResponse response) throws Exception {
		logger.info("findProcessInfo >>>> params：" + params);
		response.setContentType("text/html;charset=UTF-8");
		TMUtil.setHeader(response);
		PrintWriter out = response.getWriter();
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			JSONObject paramsObj = new JSONObject(params);
			String wfprocessOid = "";
			if(paramsObj.has("wfprocessOid")) {
				wfprocessOid = paramsObj.getString("wfprocessOid");
			}
			JSONObject xmlInfo = processService.getFormDataXml(wfprocessOid);
			
			WfProcess process = (WfProcess) TMUtil.oid2Obj(wfprocessOid);
			
			JSONObject obj = new JSONObject();
			obj.put(ProcessService.ACTIVITYSINFO, planactivityservice.getPlanActivityView(process));
			obj.put(ProcessService.PROJECTiNFO, xmlInfo.getJSONObject(ProcessService.PROJECTiNFO));
			out.print(obj.toString());
			
//			//构造测试数据
//			JSONObject paramsObj = new JSONObject(params);
//			String wfprocessOid = "";
//			if(paramsObj.has("wfprocessOid")) {
//				wfprocessOid = paramsObj.getString("wfprocessOid");
//				WfProcess process = (WfProcess) TMUtil.oid2Obj(wfprocessOid);
//				Project2 project = (Project2) TMUtil.oid2Obj(process.getBusinessObjReference());
//				JSONObject obj = new JSONObject();
//				JSONObject activitysInfo = planactivityservice.getPlanActivityView(project, true);
//				JSONObject projectInfo = projectservice.findAPQP(project);
//				obj.put(ProcessService.ACTIVITYSINFO, activitysInfo);
//				obj.put(ProcessService.PROJECTiNFO, projectInfo);
//				out.print(obj.toString());
//			}
			
		} catch (WTException e) {
			JSONObject xmlInfo = new JSONObject();
			e.printStackTrace();
			logger.error("queryAPQPs >>>catch >>>>>: " + e.getLocalizedMessage(Locale.getDefault()));
			xmlInfo.put("msg", e.getLocalizedMessage(Locale.getDefault()));
			xmlInfo.put("code", "1");
			out.print(xmlInfo.toString());
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
//	/**
//	 * 资料驳回
//	 * @param planActivityOid
//	 * @param response
//	 * @throws Exception
//	 * @author xucr
//	 * @CreateDate 2020年8月31日
//	 */
//	@RequestMapping(value = "/reject", method = { RequestMethod.POST, RequestMethod.GET })
//	public void reject(
//			@RequestParam(value = "params", required = false) String params,
//			HttpServletResponse response) throws Exception {
//		/**
//		 * 该驳回并非针对流程驳回
//		 * */
//		response.setContentType("text/html;charset=UTF-8");
//		TMUtil.setHeader(response);
//		JSONObject result = null;
//		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
//		logger.info("reject >>>> params：" + params);
//		PrintWriter out = response.getWriter();
//		try {
//			result = processService.reject(params);
//			out.print(result.toString());
//		} catch (WTException e) {
//			result = new JSONObject();
//			e.printStackTrace();
//			logger.error("reject >>>catch >>>>>: " + e.getLocalizedMessage(Locale.getDefault()));
//			result.put("msg", e.getLocalizedMessage(Locale.getDefault()));
//			result.put("code", "1");
//			out.print(result.toString());
//		} finally {
//			SessionServerHelper.manager.setAccessEnforced(enforce);
//		}
//	}
	
	/**
	 * 资料驳回
	 * @param planActivityOid
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年8月31日
	 */
	@RequestMapping(value = "/reject", method = { RequestMethod.POST, RequestMethod.GET })
	public void reject(
			@RequestParam(value = "params", required = false) String params,
			HttpServletResponse response) throws Exception {
		/**
		 * 该驳回并非针对流程驳回，而是记录需要驳回的任务，待流程结束时，再修改这些活动的状态
		 * */
		response.setContentType("text/html;charset=UTF-8");
		TMUtil.setHeader(response);
		JSONObject result = null;
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		logger.info("reject >>>> params：" + params);
		PrintWriter out = response.getWriter();
		try {
			result = processService.reject(params);
			out.print(result.toString());
		} catch (WTException e) {
			result = new JSONObject();
			e.printStackTrace();
			logger.error("reject >>>catch >>>>>: " + e.getLocalizedMessage(Locale.getDefault()));
			result.put("msg", e.getLocalizedMessage(Locale.getDefault()));
			result.put("code", "1");
			out.print(result.toString());
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
}
